package org.frog.sgs.client;

import java.net.InetSocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFactory;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.frog.sgs.card.Card;
import org.frog.sgs.client.game.ClientInstance;
import org.frog.sgs.consts.Constants;
import org.frog.sgs.data.GameDataManager;
import org.frog.sgs.io.SgsCodecFactory;

/**
 * @author duanxiangqi
 * @date 2012-10-22
 */
public class SgsClient {

	public static void main(String[] args) throws Exception {
		new SgsClient().startup();
	}

	private NioSocketConnector connector;

	private IoSession session;

	private ClientInstance instance;

	public void startup() throws Exception {
		System.out.println("====================================");
		System.out.println(Card.VERSION);
		System.out.println("====================================");

		GameDataManager.instance.init();

		connector = new NioSocketConnector(1);

		ClientIoHandler ioHandler = new ClientIoHandler();
		ioHandler.setClient(this);

		connector.setHandler(ioHandler);
		connector.setConnectTimeoutMillis(Constants.CLIENT_TIMEOUT);
		connector.getSessionConfig().setKeepAlive(false);
		connector.getSessionConfig().setReadBufferSize(Constants.CLIENT_SESSION_BUFFER_SIZE);// 发送缓冲区1M
		connector.getSessionConfig().setReceiveBufferSize(Constants.CLIENT_SESSION_BUFFER_SIZE);// 接收缓冲区1M

		ProtocolCodecFactory codecFactory = new SgsCodecFactory();
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(codecFactory));

		try {
			ConnectFuture connect = connector
					.connect(new InetSocketAddress(Constants.SERVER_IP, Constants.SERVER_PORT));
			session = connect.awaitUninterruptibly().getSession();
			System.out.println("连接服务器成功【" + Constants.SERVER_IP + ":" + Constants.SERVER_PORT + "】");
			instance = new ClientInstance(session);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("连接服务器失败【" + Constants.SERVER_IP + ":" + Constants.SERVER_PORT + "】");
			stop();
		}
	}

	public void stop() {
		System.exit(0);
	}

	public NioSocketConnector getConnector() {
		return connector;
	}

	public IoSession getSession() {
		return session;
	}

	public ClientInstance getInstance() {
		return instance;
	}
}
